/*
 *  linux/kernel/mktime.c
 *
 *  (C) 1991  Linus Torvalds
 */

#include <time.h>

/*
 * This isn't the library routine, it is only used in the kernel.
 * as such, we don't care about years<1970 etc, but assume everything
 * is ok. Similarly, TZ etc is happily ignored. We just do everything
 * as easily as possible. Let's find something public for the library
 * routines (although I think minix times is public).
 */
/*
 * PS. I hate whoever though up the year 1970 - couldn't they have gotten
 * a leap-year instead? I also hate Gregorius, pope or no. I'm grumpy.
 */
#define MINUTE 60
#define HOUR (60*MINUTE)
#define DAY (24*HOUR)
#define YEAR (365*DAY)

/* interestingly, we assume leap-years */
// 可以学习下其查表算法
static int month[12] = {
	0,					// 0月的秒数
	DAY*(31),			// 1-1月的秒数
	DAY*(31+29),		// 1-2月的秒数
	DAY*(31+29+31),		// 1-3月的秒数
	DAY*(31+29+31+30),
	DAY*(31+29+31+30+31),
	DAY*(31+29+31+30+31+30),
	DAY*(31+29+31+30+31+30+31),
	DAY*(31+29+31+30+31+30+31+31),
	DAY*(31+29+31+30+31+30+31+31+30),
	DAY*(31+29+31+30+31+30+31+31+30+31),
	DAY*(31+29+31+30+31+30+31+31+30+31+30)		// 一年所有月的秒数
};

// 将tm结构中的时间转换为UNIX日历时间，即从1970-1-1 0点开始的秒数
// 大致了解其计算思路即可，不需要了解其具体实现算法，没有太大必要
// 特别是其中有关闰年方面的处理等

// mktime()在gcc库中有，但内核不能使用这种库，所以这里为内核调用实现
// 该函数在main.c中调用time_init，用于获取系统启动时间
long kernel_mktime(struct tm * tm)
{
	long res;
	int year;

	year = tm->tm_year - 70;		// 相对年数
/* magic offsets (y+1) needed to get leapyears right.*/
	res = YEAR*year + DAY*((year+1)/4);	// 只算年份经历的秒数
	res += month[tm->tm_mon];		// 加上月份经历的秒数


/* and (y+2) here. If it wasn't a leap-year, we have to adjust */
	if (tm->tm_mon>1 && ((year+2)%4))	// 闰年调整，要不要减去一天的秒数
		res -= DAY;
	res += DAY*(tm->tm_mday-1);		// 加上天数到现在的秒数
	res += HOUR*tm->tm_hour;		// 小时经历的秒
	res += MINUTE*tm->tm_min;		// 分钟经历的秒
	res += tm->tm_sec;				// 最终的秒
	return res;
}
